import base64
import tkinter as tk
from tkinter import scrolledtext, messagebox

# 与utils.py中的set_window_icon_from_base64完全相同, 只是在这里单独写了一份, 免得来回import
def set_window_icon_from_base64(root: tk.Tk, base64_icon=None):
    """
    设置 tkinter 窗口图标, 图标数据以 Base64 编码形式传递。

    :param root: Tk() 实例或 Toplevel() 实例
    :param base64_icon: Base64 编码的图标数据, 可选(默认为简单的 GIF 图标)
    """
    # 默认的 Base64 编码 GIF 图标数据
    default_icon = "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAAAXNSR0IArs4c6QAAAdZJREFUeF7tmk1OwzAQhWeg7FFPkEoUiVtwlHaZXgJ6Cbpsb8IxkACpOUHEnipGgU1rBM+OQf7J6/b5Z+abN04qR2XkPx15/kIAdMDICbAFRm4AHoJsAbbAyAmwBVwMcLl5qs7k4k5MdyuilcucdMaYxog2Rg/Lt/qmseOCDvhM3kz26SQ0PJJODzMbAgQw3bxuxZjF8G0Tmqly39bz9XFEGMDDi0koheBQ2tX8JGdvAPYCwRH98wJTq4AEQAewBf72DEA9lroefAimniCKjwDQUwgRzF0PdgACGFtHBSIAVCFEEM2PraP46QBUIUTQ1u317Hdv3/XQ/ND9gh1AAODvMqpgqE4HWAR8gQa3ADpDYuvozCEAVCFEEM2PraP46QBUIUTQV0f7Id33kEPxBTsAbYDeE1DCoY85FB8BoAoggr462g/pybUACji2jgoU3AKxE0T7EwBvhk7vNgdcjT3v8/sm4KfGME27up4dq/gMKOp6XHdtfbX0AvD1gcT5Y/4u+F79HgR0QD+oh6BmslUxVZYgVHedvK8HfSKDHjO5604OyD3J3+IngJKr65IbHeBCqeQxdEDJ1XXJjQ5woVTyGDqg5Oq65EYHuFAqeQwdUHJ1XXL7AKF/3lBxkE7hAAAAAElFTkSuQmCC"

    # 如果用户没有提供 base64_icon, 使用默认值
    if base64_icon is None:
        base64_icon = default_icon

    try:
        # 解码 Base64 数据为二进制
        decoded_icon = base64.b64decode(base64_icon)
    except Exception as e:
        raise ValueError(
            "Failed to decode Base64 data. Please check the input data."
        ) from e

    try:
        # 将二进制数据加载为 PhotoImage 对象
        icon = tk.PhotoImage(data=decoded_icon)
    except Exception as e:
        raise ValueError(
            "Failed to load the icon image. Please ensure it's a valid image format."
        ) from e

    try:
        # 设置窗口图标
        root.tk.call("wm", "iconphoto", root._w, icon)
    except Exception as e:
        raise ValueError(
            "Failed to set the window icon. Please check if the window is properly initialized."
        ) from e

    return icon

def show_js(
    userscript_code,
    window_title="油猴脚本",
    background_color="#1a1b16",
    text_color="white",
    parent=None,
):
    # 使用传入的父窗口，如果没有父窗口，则创建一个新的主窗口
    if parent:
        root = tk.Toplevel(parent)
    else:
        root = tk.Tk()

    root.title(window_title)
    root.geometry("800x600")
    root.configure(bg=background_color)
    set_window_icon_from_base64(root)

    # 创建一个可滚动的文本框
    text_area = scrolledtext.ScrolledText(
        root,
        wrap=tk.WORD,
        width=100,
        height=30,
        bg=background_color,
        fg=text_color,
        undo=True,
    )
    text_area.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)

    # 插入代码到文本框
    text_area.insert(tk.END, userscript_code)
    # 插入代码后禁用文本框
    text_area.config(state="disabled")

    # 添加复制按钮
    def copy_to_clipboard():
        # root.clipboard_clear()
        root.clipboard_append(text_area.get("1.0", tk.END))
        # 显示复制成功消息
        messagebox.showinfo("复制成功", "脚本代码已复制到剪贴板！")

    copy_button = tk.Button(
        root,
        text="一键复制",
        command=copy_to_clipboard,
        bg=background_color,
        fg=text_color,
        activebackground="#535544",
        activeforeground=text_color,
        cursor="hand2",
        width=10,
        height=2,
    )
    copy_button.pack(pady=20)

    def on_enter(event):
        event.widget.config(bg="#292a22")

    def on_leave(event):
        event.widget.config(bg=background_color)

    copy_button.bind("<Enter>", on_enter)
    copy_button.bind("<Leave>", on_leave)

    # 如果这是一个子窗口，那么不需要主循环
    if not parent:
        root.mainloop()


if __name__ == "__main__":
    userscript_code = """// ==UserScript==
// @name        Example Script
// @namespace   http://tampermonkey.net/
// @version     1.0
// @description 示例油猴脚本
// @author      Example User
// @match       *://*/*
// @grant       none
// ==/UserScript==

(function() {
    'use strict';

    alert('这是一条来自油猴脚本的消息！');
})();"""
    # 创建一个主窗口
    main_root = tk.Tk()
    main_root.title("主窗口")
    main_root.geometry("400x300")

    # 创建一个按钮来打开显示脚本的窗口
    def open_script_window():
        show_js(userscript_code, parent=main_root)

    open_button = tk.Button(main_root, text="打开脚本窗口", command=open_script_window)
    open_button.pack(pady=20)

    # 运行主循环
    main_root.mainloop()
